module.exports = class DoubleEndQueue {
    // 队列容器
    #items = {}
    // 队列头指针
    #headPointer = 0
    // 队列尾指针
    #endPointer = 0

    // 后端入队
    addFromEnd(data) {
        this.#items[this.#endPointer] = data
        this.#endPointer++
    }

    // 前端入队
    addFromHead(data) {
        // 所有队列元素后移一位
        for (let i = this.#endPointer; i > this.#headPointer; i--) {
            this.#items[i] = this.#items[i - 1]
        }
        // 头部入队
        this.#items[this.#headPointer] = data
        this.#endPointer++
    }

    // 前端出队
    removeFromHead() {
        if (this.isEmpty()) {
            return
        }
        const res = this.#items[this.#headPointer]
        delete this.#items[this.#headPointer]
        this.#headPointer++
        return res
    }

    // 后端出队
    removeFromEnd() {
        if (this.isEmpty()) {
            return
        }
        const res = this.#items[this.#endPointer - 1]
        // 删掉最后一个队列元素
        delete this.#items[this.#endPointer - 1]
        // 尾指针前移
        this.#endPointer--
        return res
    }

    // 读取队头
    peekHead() {
        return this.#items[this.#headPointer]
    }

    // 读取队尾
    peekEnd() {
        return this.#items[this.#endPointer - 1]
    }

    // 队列容量
    size() {
        return this.#endPointer - this.#headPointer
    }

    // 是否是空队列
    isEmpty() {
        return this.size() === 0
    }

    toString() {
        let str = ''
        for (let i = this.#headPointer; i < this.#endPointer; i++) {
            str += `${this.#items[i]} `
        }
        return str
    }
}